package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"

	"github.com/mark3labs/mcp-go/mcp"
)

// parseArguments 解析请求参数的辅助函数
func parseArguments(arguments any, target interface{}) error {
	argsBytes, ok := arguments.([]byte)
	if !ok {
		var err error
		argsBytes, err = json.Marshal(arguments)
		if err != nil {
			return fmt.Errorf("failed to marshal arguments: %v", err)
		}
	}
	return json.Unmarshal(argsBytes, target)
}

// 作业管理处理函数
func (j *JenkinsMCPServer) handleCreateJob(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	// 获取作业配置参数
	jobConfigData := request.GetArguments()["job_config"]
	if jobConfigData == nil {
		return mcp.NewToolResultError("job_config 参数是必需的"), nil
	}

	// 将参数转换为 JobConfig 结构
	var jobConfig JobConfig
	if err := parseArguments(jobConfigData, &jobConfig); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析作业配置失败: %v", err)), nil
	}

	// 构建作业配置 XML
	configXML, err := j.buildJobConfigXML(jobConfig)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("构建作业配置失败: %v", err)), nil
	}

	// 发送请求创建作业
	endpoint := fmt.Sprintf("/createItem?name=%s", jobConfig.Name)
	resp, err := j.makeRequest("POST", endpoint, []byte(configXML))
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("创建作业失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return mcp.NewToolResultError(fmt.Sprintf("创建作业失败，状态码: %d，错误: %s", resp.StatusCode, string(body))), nil
	}

	return mcp.NewToolResultText(fmt.Sprintf("作业 '%s' 创建成功", jobConfig.Name)), nil
}

func (j *JenkinsMCPServer) handleBuildJob(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	// 获取作业名称
	jobName, err := request.RequireString("job_name")
	if err != nil {
		return mcp.NewToolResultError("job_name 参数是必需的"), nil
	}

	// 获取可选参数
	args := request.GetArguments()
	var parameters map[string]interface{}
	if paramData, ok := args["parameters"]; ok && paramData != nil {
		if paramMap, ok := paramData.(map[string]interface{}); ok {
			parameters = paramMap
		}
	}

	// 构建端点
	endpoint := fmt.Sprintf("/job/%s/build", jobName)
	if len(parameters) > 0 {
		endpoint = fmt.Sprintf("/job/%s/buildWithParameters", jobName)
	}

	// 准备参数
	var body []byte
	if len(parameters) > 0 {
		paramData, err := json.Marshal(parameters)
		if err != nil {
			return mcp.NewToolResultError(fmt.Sprintf("序列化参数失败: %v", err)), nil
		}
		body = paramData
	}

	// 发送构建请求
	resp, err := j.makeRequest("POST", endpoint, body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("构建作业失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
		respBody, _ := io.ReadAll(resp.Body)
		return mcp.NewToolResultError(fmt.Sprintf("构建作业失败，状态码: %d，错误: %s", resp.StatusCode, string(respBody))), nil
	}

	result := fmt.Sprintf("作业 '%s' 构建已启动", jobName)
	return mcp.NewToolResultText(result), nil
}

func (j *JenkinsMCPServer) handleGetJobInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	jobName, err := request.RequireString("job_name")
	if err != nil {
		return mcp.NewToolResultError("job_name 参数是必需的"), nil
	}

	endpoint := fmt.Sprintf("/job/%s/api/json", jobName)
	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取作业信息失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取作业信息失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var jobInfo map[string]interface{}
	if err := json.Unmarshal(body, &jobInfo); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析作业信息失败: %v", err)), nil
	}

	result, _ := json.MarshalIndent(jobInfo, "", "  ")
	return mcp.NewToolResultText(string(result)), nil
}

func (j *JenkinsMCPServer) handleGetBuildInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	jobName, err := request.RequireString("job_name")
	if err != nil {
		return mcp.NewToolResultError("job_name 参数是必需的"), nil
	}

	args := request.GetArguments()
	buildNumberValue, ok := args["build_number"]
	if !ok {
		return mcp.NewToolResultError("build_number 参数是必需的"), nil
	}

	buildNumber := 0
	switch v := buildNumberValue.(type) {
	case float64:
		buildNumber = int(v)
	case int:
		buildNumber = v
	case string:
		if num, parseErr := strconv.Atoi(v); parseErr == nil {
			buildNumber = num
		} else {
			return mcp.NewToolResultError("build_number 必须是数字"), nil
		}
	default:
		return mcp.NewToolResultError("build_number 参数格式错误"), nil
	}

	endpoint := fmt.Sprintf("/job/%s/%d/api/json", jobName, buildNumber)
	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取构建信息失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取构建信息失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var buildInfo map[string]interface{}
	if err := json.Unmarshal(body, &buildInfo); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析构建信息失败: %v", err)), nil
	}

	result, _ := json.MarshalIndent(buildInfo, "", "  ")
	return mcp.NewToolResultText(string(result)), nil
}

func (j *JenkinsMCPServer) handleGetBuildLog(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	jobName, err := request.RequireString("job_name")
	if err != nil {
		return mcp.NewToolResultError("job_name 参数是必需的"), nil
	}

	args := request.GetArguments()
	buildNumberValue, ok := args["build_number"]
	if !ok {
		return mcp.NewToolResultError("build_number 参数是必需的"), nil
	}

	buildNumber := 0
	switch v := buildNumberValue.(type) {
	case float64:
		buildNumber = int(v)
	case int:
		buildNumber = v
	default:
		return mcp.NewToolResultError("build_number 参数格式错误"), nil
	}

	endpoint := fmt.Sprintf("/job/%s/%d/consoleText", jobName, buildNumber)

	if startValue, ok := args["start"]; ok {
		if start, ok := startValue.(float64); ok && start > 0 {
			endpoint += fmt.Sprintf("?start=%d", int(start))
		}
	}

	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取构建日志失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取构建日志失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	return mcp.NewToolResultText(string(body)), nil
}

func (j *JenkinsMCPServer) handleDeleteJob(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	jobName, err := request.RequireString("job_name")
	if err != nil {
		return mcp.NewToolResultError("job_name 参数是必需的"), nil
	}

	endpoint := fmt.Sprintf("/job/%s/doDelete", jobName)
	resp, err := j.makeRequest("POST", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("删除作业失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusFound {
		return mcp.NewToolResultError(fmt.Sprintf("删除作业失败，状态码: %d", resp.StatusCode)), nil
	}

	return mcp.NewToolResultText(fmt.Sprintf("作业 '%s' 删除成功", jobName)), nil
}

func (j *JenkinsMCPServer) handleListJobs(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	args := request.GetArguments()
	folder := ""
	if folderValue, ok := args["folder"]; ok {
		if folderStr, ok := folderValue.(string); ok {
			folder = folderStr
		}
	}

	endpoint := "/api/json"
	if folder != "" {
		endpoint = fmt.Sprintf("/job/%s/api/json", folder)
	}

	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("列出作业失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("列出作业失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析作业列表失败: %v", err)), nil
	}

	jobsData, _ := json.MarshalIndent(result, "", "  ")
	return mcp.NewToolResultText(string(jobsData)), nil
}

// 更新作业配置
func (j *JenkinsMCPServer) handleUpdateJob(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	jobName, err := request.RequireString("job_name")
	if err != nil {
		return mcp.NewToolResultError("job_name 参数是必需的"), nil
	}

	// 获取作业配置参数
	jobConfigData := request.GetArguments()["job_config"]
	if jobConfigData == nil {
		return mcp.NewToolResultError("job_config 参数是必需的"), nil
	}

	// 将参数转换为 JobConfig 结构
	var jobConfig JobConfig
	if err := parseArguments(jobConfigData, &jobConfig); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析作业配置失败: %v", err)), nil
	}

	// 构建作业配置 XML
	configXML, err := j.buildJobConfigXML(jobConfig)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("构建作业配置失败: %v", err)), nil
	}

	// 发送请求更新作业配置
	endpoint := fmt.Sprintf("/job/%s/config.xml", jobName)
	resp, err := j.makeRequest("POST", endpoint, []byte(configXML))
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("更新作业失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return mcp.NewToolResultError(fmt.Sprintf("更新作业失败，状态码: %d，错误: %s", resp.StatusCode, string(body))), nil
	}

	return mcp.NewToolResultText(fmt.Sprintf("作业 '%s' 更新成功", jobName)), nil
}

// 获取节点信息
func (j *JenkinsMCPServer) handleGetNodeInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	args := request.GetArguments()
	nodeName := ""
	if nodeNameValue, ok := args["node_name"]; ok {
		if nodeNameStr, ok := nodeNameValue.(string); ok {
			nodeName = nodeNameStr
		}
	}

	var endpoint string
	if nodeName == "" {
		// 获取所有节点信息
		endpoint = "/computer/api/json"
	} else {
		// 获取特定节点信息
		endpoint = fmt.Sprintf("/computer/%s/api/json", nodeName)
	}

	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取节点信息失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取节点信息失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var nodeInfo map[string]interface{}
	if err := json.Unmarshal(body, &nodeInfo); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析节点信息失败: %v", err)), nil
	}

	result, _ := json.MarshalIndent(nodeInfo, "", "  ")
	return mcp.NewToolResultText(string(result)), nil
}

// 创建凭据
func (j *JenkinsMCPServer) handleCreateCredential(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	credentialID, err := request.RequireString("credential_id")
	if err != nil {
		return mcp.NewToolResultError("credential_id 参数是必需的"), nil
	}

	credentialType, err := request.RequireString("type")
	if err != nil {
		return mcp.NewToolResultError("type 参数是必需的"), nil
	}

	configData := request.GetArguments()["config"]
	if configData == nil {
		return mcp.NewToolResultError("config 参数是必需的"), nil
	}

	var config map[string]interface{}
	if err := parseArguments(configData, &config); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析凭据配置失败: %v", err)), nil
	}

	// 构建凭据配置 JSON
	credentialConfig := map[string]interface{}{
		"": "0",
		"credentials": map[string]interface{}{
			"scope":       "GLOBAL",
			"id":          credentialID,
			"description": config["description"],
		},
	}

	// 根据凭据类型设置特定配置
	switch credentialType {
	case "usernamePassword":
		credentialConfig["credentials"].(map[string]interface{})["$class"] = "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
		credentialConfig["credentials"].(map[string]interface{})["username"] = config["username"]
		credentialConfig["credentials"].(map[string]interface{})["password"] = config["password"]
	case "secretText":
		credentialConfig["credentials"].(map[string]interface{})["$class"] = "org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl"
		credentialConfig["credentials"].(map[string]interface{})["secret"] = config["secret"]
	case "sshUserPrivateKey":
		credentialConfig["credentials"].(map[string]interface{})["$class"] = "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
		credentialConfig["credentials"].(map[string]interface{})["username"] = config["username"]
		credentialConfig["credentials"].(map[string]interface{})["privateKeySource"] = map[string]interface{}{
			"stapler-class": "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource",
			"privateKey":    config["privateKey"],
		}
	default:
		return mcp.NewToolResultError(fmt.Sprintf("不支持的凭据类型: %s", credentialType)), nil
	}

	jsonData, err := json.Marshal(credentialConfig)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("序列化凭据配置失败: %v", err)), nil
	}

	endpoint := "/credentials/store/system/domain/_/createCredentials"
	resp, err := j.makeRequest("POST", endpoint, jsonData)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("创建凭据失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusFound {
		body, _ := io.ReadAll(resp.Body)
		return mcp.NewToolResultError(fmt.Sprintf("创建凭据失败，状态码: %d，错误: %s", resp.StatusCode, string(body))), nil
	}

	return mcp.NewToolResultText(fmt.Sprintf("凭据 '%s' 创建成功", credentialID)), nil
}

// 获取插件信息
func (j *JenkinsMCPServer) handleGetPluginInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	args := request.GetArguments()
	pluginName := ""
	if pluginNameValue, ok := args["plugin_name"]; ok {
		if pluginNameStr, ok := pluginNameValue.(string); ok {
			pluginName = pluginNameStr
		}
	}

	endpoint := "/pluginManager/api/json?depth=1"
	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取插件信息失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取插件信息失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var pluginInfo map[string]interface{}
	if err := json.Unmarshal(body, &pluginInfo); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析插件信息失败: %v", err)), nil
	}

	// 如果指定了插件名称，过滤结果
	if pluginName != "" {
		plugins, ok := pluginInfo["plugins"].([]interface{})
		if ok {
			for _, plugin := range plugins {
				if pluginMap, ok := plugin.(map[string]interface{}); ok {
					if shortName, ok := pluginMap["shortName"].(string); ok && shortName == pluginName {
						result, _ := json.MarshalIndent(pluginMap, "", "  ")
						return mcp.NewToolResultText(string(result)), nil
					}
				}
			}
			return mcp.NewToolResultError(fmt.Sprintf("未找到插件: %s", pluginName)), nil
		}
	}

	result, _ := json.MarshalIndent(pluginInfo, "", "  ")
	return mcp.NewToolResultText(string(result)), nil
}

// 安装插件
func (j *JenkinsMCPServer) handleInstallPlugin(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	pluginName, err := request.RequireString("plugin_name")
	if err != nil {
		return mcp.NewToolResultError("plugin_name 参数是必需的"), nil
	}

	args := request.GetArguments()
	version := ""
	if versionValue, ok := args["version"]; ok {
		if versionStr, ok := versionValue.(string); ok {
			version = versionStr
		}
	}

	// 构建插件安装请求
	pluginSpec := pluginName
	if version != "" {
		pluginSpec = fmt.Sprintf("%s@%s", pluginName, version)
	}

	endpoint := "/pluginManager/installNecessaryPlugins"

	// 构建表单数据
	formData := fmt.Sprintf(`<jenkins><install plugin="%s" /></jenkins>`, pluginSpec)

	resp, err := j.makeRequest("POST", endpoint, []byte(formData))
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("安装插件失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusFound {
		body, _ := io.ReadAll(resp.Body)
		return mcp.NewToolResultError(fmt.Sprintf("安装插件失败，状态码: %d，错误: %s", resp.StatusCode, string(body))), nil
	}

	return mcp.NewToolResultText(fmt.Sprintf("插件 '%s' 安装请求已提交", pluginSpec)), nil
}

// 获取构建队列信息
func (j *JenkinsMCPServer) handleGetQueueInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	endpoint := "/queue/api/json"
	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取队列信息失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取队列信息失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var queueInfo map[string]interface{}
	if err := json.Unmarshal(body, &queueInfo); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析队列信息失败: %v", err)), nil
	}

	result, _ := json.MarshalIndent(queueInfo, "", "  ")
	return mcp.NewToolResultText(string(result)), nil
}

// 获取系统信息
func (j *JenkinsMCPServer) handleGetSystemInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	endpoint := "/systemInfo/api/json"
	resp, err := j.makeRequest("GET", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("获取系统信息失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return mcp.NewToolResultError(fmt.Sprintf("获取系统信息失败，状态码: %d", resp.StatusCode)), nil
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("读取响应失败: %v", err)), nil
	}

	var systemInfo map[string]interface{}
	if err := json.Unmarshal(body, &systemInfo); err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("解析系统信息失败: %v", err)), nil
	}

	result, _ := json.MarshalIndent(systemInfo, "", "  ")
	return mcp.NewToolResultText(string(result)), nil
}

// 重启Jenkins
func (j *JenkinsMCPServer) handleRestartJenkins(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
	args := request.GetArguments()
	safeRestart := false
	if safeRestartValue, ok := args["safe_restart"]; ok {
		if safeRestartBool, ok := safeRestartValue.(bool); ok {
			safeRestart = safeRestartBool
		}
	}

	var endpoint string
	if safeRestart {
		endpoint = "/safeRestart"
	} else {
		endpoint = "/restart"
	}

	resp, err := j.makeRequest("POST", endpoint, nil)
	if err != nil {
		return mcp.NewToolResultError(fmt.Sprintf("重启Jenkins失败: %v", err)), nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusFound {
		body, _ := io.ReadAll(resp.Body)
		return mcp.NewToolResultError(fmt.Sprintf("重启Jenkins失败，状态码: %d，错误: %s", resp.StatusCode, string(body))), nil
	}

	restartType := "立即重启"
	if safeRestart {
		restartType = "安全重启"
	}

	return mcp.NewToolResultText(fmt.Sprintf("Jenkins %s请求已提交", restartType)), nil
}

// 辅助函数
func (j *JenkinsMCPServer) buildJobConfigXML(config JobConfig) (string, error) {
	// 根据作业类型构建不同的配置 XML
	switch config.Type {
	case "freestyle":
		return j.buildFreestyleJobXML(config)
	case "pipeline":
		return j.buildPipelineJobXML(config)
	default:
		return "", fmt.Errorf("unsupported job type: %s", config.Type)
	}
}

func (j *JenkinsMCPServer) buildFreestyleJobXML(config JobConfig) (string, error) {
	// 构建自由风格作业的 XML 配置
	xml := `<?xml version="1.0" encoding="UTF-8"?>
<project>
    <actions/>
    <description>` + config.Description + `</description>
    <keepDependencies>false</keepDependencies>
    <properties/>
    <scm class="hudson.scm.NullSCM"/>
    <canRoam>true</canRoam>
    <disabled>false</disabled>
    <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
    <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
    <triggers/>
    <concurrentBuild>false</concurrentBuild>
    <builders/>
    <publishers/>
    <buildWrappers/>
</project>`
	return xml, nil
}

func (j *JenkinsMCPServer) buildPipelineJobXML(config JobConfig) (string, error) {
	// 构建流水线作业的 XML 配置
	script := ""
	if scriptValue, ok := config.Config["script"]; ok {
		script = fmt.Sprintf("%v", scriptValue)
	}

	xml := `<?xml version="1.0" encoding="UTF-8"?>
<flow-definition plugin="workflow-job@2.40">
    <actions/>
    <description>` + config.Description + `</description>
    <keepDependencies>false</keepDependencies>
    <properties/>
    <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.87">
        <script>` + script + `</script>
        <sandbox>true</sandbox>
    </definition>
    <triggers/>
    <disabled>false</disabled>
</flow-definition>`
	return xml, nil
}
